clear;

I = imread("-3eeee42b757f1641.jpg");
% I = [1,2,5,9; 1,3,1,0; 1 2 3 8];
I=rgb2gray(I);
I=im2uint8(I);

[M,N,sig] = encode(I);
out = decode(M,N,sig);

subplot(121),imshow(I),title("原图");
% subplot(122),imshow(out),title("编解码后");

function [M, N, out] = encode(in)
    s=size(in);
    M=s(1);
    N=s(2);
    data=in(:);
    out=zeros(1, 'uint8');
    out(1)=data(1);
    carry = out(1);
    out(2)=1;
    k=1;
    for i = 2:length(data)
        if carry==data(i)
            out(k+1)=out(k+1)+1;
        else
            k=k+2;
            carry=data(i);
            out(k)=carry;
            out(k+1)=1;
        end
    end
    out=out';
end

function output = decode(M,N,sig)
    output=zeros(M,N,'uint8');
    originSig = zeros([1, M*N],"uint8");
    k=double(1);
    l=1;
    M=double(M);
    for i=1:2:uint32(length(sig))
        num = sig(i+1);
        while num>0
%             output(mod(k-1,M)+1, fix((k-1)/M)+1)=sig(i);
            originSig(l) = sig(i);
            l=l+1;
            k=k+1;
            num = num-1;
        end
        output = originSig;
%         output = reshape(originSig,[M,N]);
    end
end